package com.ruoyi.standingbook.v2toilet.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.standingbook.v2toilet.bill.BillFlowUtil;
import com.ruoyi.standingbook.v2toilet.ToiletConst;
import com.ruoyi.standingbook.v2toilet.bill.BillReceiveBean;
import com.ruoyi.standingbook.v2toilet.domain.bo.V2ToiletBillBo;
import com.ruoyi.standingbook.v2toilet.domain.bo.V2ToiletBo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletBillVo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletImpDetailVo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletVo;
import com.ruoyi.standingbook.v2toilet.enums.ItemStatusEnum;
import com.ruoyi.standingbook.v2toilet.service.IToiletBillService;
import com.ruoyi.standingbook.v2toilet.service.IToiletImpDetailService;
import com.ruoyi.standingbook.v2toilet.service.IToiletService;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class V2ExtendProcessService {
    private final IToiletService iToiletService;
    private final IToiletImpDetailService iToiletImpDetailService;
    private final IToiletBillService iToiletBillService;
    private final ISysConfigService configService;
    private final V2ExtendAsyncService apiLogService;

    /**
     * 保存excel数据
     */
    @Transactional
    public void saveExcelData(List<V2ToiletImpDetailVo> result, List<V2ToiletBillBo> bills, Map<String, Object> query) {
        //找到已经改变的 按管养日期和修改状态
        List<String> toiletsChanged = iToiletService.listChanged(query);
        //排除改变的
        List<V2ToiletImpDetailVo> toSaveDetail = result.stream().filter(e -> !toiletsChanged.contains(e.getId())).collect(Collectors.toList());
        log.info("toilet changed size:{},detail size:{},saved size {}", toiletsChanged.size(), result.size(), toSaveDetail);
        if (toSaveDetail.isEmpty()) {
            return;
        }

        boolean saved = this.iToiletImpDetailService.batchInsertOrUpdate(toSaveDetail);//保存明细
        if (saved) saved = this.iToiletService.batchInsertOrUpdate(toSaveDetail);//明细表数据转到主表
        if (saved) {
            // 找到数据发生变化的 状态大于0的
            List<String> changedBill = iToiletBillService.listChangeInfo(query);
            //排除未改变的,剩下的就是可以更新或新增的
            List<V2ToiletBillBo> toSaved = bills.stream().filter(e -> !changedBill.contains(e.getId())).collect(Collectors.toList());
            //            toSaved = toSaved.stream().filter(e -> !changedToilet.contains(e.getId())).collect(Collectors.toList());
            toSaved = toSaved.stream().map(BillFlowUtil::setFlow).collect(Collectors.toList());
            if (toSaved.isEmpty()) return;
            this.iToiletBillService.batchInsertOrUpdate(toSaved);
        }

    }


    @Transactional
    public R<Void> receiveBill(final BillReceiveBean receiveData) {
        log.info(" api.receive<<<<<<<< {}", JSONUtil.toJsonStr(receiveData));
        if (Objects.isNull(receiveData.getFlowCode())) {
            log.warn("api.receive 流水号不能为空！");
            return R.fail("流水号不能为空");
        }
        //根据
//        V2ToiletBillVo tmpVo = iToiletBillService.queryByFlowCode(ItemStatusEnum.COMMIT, receiveData.getFlowCode());
        V2ToiletBillBo bo = new V2ToiletBillBo();
        bo.setFlowCode(receiveData.getFlowCode());
        bo.setStatus(ItemStatusEnum.COMMIT.intCode);//99
        bo.setModified(ToiletConst.MODIFY_NOT);//1
        V2ToiletBillVo tmpVo = iToiletBillService.queryOne(bo);
        if (Objects.isNull(tmpVo)) {
            log.warn("api.receive 巡检项数据未找到！");
            return R.warn("巡检项数据未找到");
        }

        SysOss oss = null;
        String afterImage = null;
        if (StringUtils.isNotBlank(receiveData.getImage())) {
            oss = apiLogService.bytesUpload(receiveData.getFlowCode(), receiveData.getImage());
        }
        //设置主表
        V2ToiletBo toiletBo = new V2ToiletBo();
        //-------设置巡检项为绿色正常
        JSONObject jsonObject = JSONUtil.parseObj(toiletBo);
        if (Objects.nonNull(oss)) {
            String afterAttr = tmpVo.getItem().concat(ToiletConst.EXCEL_IMAGE_AFTER);
            jsonObject.set(afterAttr, oss.getOssId());
            System.out.println(jsonObject.get(afterAttr));
            afterImage = oss.getUrl();
        }
        jsonObject.set(tmpVo.getItem(), receiveData.getStatus());
        toiletBo = JSONUtil.toBean(jsonObject, V2ToiletBo.class);
        //-------设置巡检项为绿色正常 END
        toiletBo.setId(tmpVo.getToiletId());
        toiletBo.setModified(ToiletConst.MODIFY_NOT);  //设置本条数据已做过调整，不可覆盖
        V2ToiletVo dbData = iToiletService.queryById(tmpVo.getToiletId());
        int processCount = (Objects.isNull(dbData.getAnomalyProcessCount()) ? 0 : dbData.getAnomalyProcessCount()) + 1;
        toiletBo.setAnomalyProcessCount(processCount > dbData.getAnomalyCount() ? dbData.getAnomalyCount() : processCount);
        iToiletService.updateByBo(toiletBo);
        //设置主表 END
        //--------------------------------------------------------
        //添加工单流程
        V2ToiletBillBo billNewFlow = BeanUtil.copyProperties(tmpVo, V2ToiletBillBo.class);
        billNewFlow.setCurrUser(receiveData.getUser());
        billNewFlow.setStatus(receiveData.getStatus());
        BillFlowUtil.setFlow(billNewFlow);//设置流程
        billNewFlow.setImageBefore(null);
        if (StringUtils.isNotBlank(afterImage)) {
            billNewFlow.setImageAfter(afterImage);//设置处理后图片
        } else {
            billNewFlow.setImageAfter(receiveData.getImage());
        }
        billNewFlow.setModified(ToiletConst.MODIFY_NOT);//不可改变
        billNewFlow.setStatus(ItemStatusEnum.ERR_TO_OK.intCode);
        iToiletBillService.updateByBo(billNewFlow);
        //添加工单流程 end
        log.info("billReceive process success");
        return R.ok();

    }


}
